<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
class Category extends CI_Controller {
	public function __construct() {
		parent::__construct ();
		if (! $this->session->userdata ( 'logged_in' )) {
			redirect ( 'passport/index' );
			exit ();
		}
	}
	/*
	 * 跳转到分类管理主页
	 */
	public function index() {
		$this->load->model ( 'category_model' );
		$data ['categories'] = $this->category_model->find_all_categories ();
		$data ['title'] = '分类管理 - '.SYSTEM_NAME;
		$this->load->view ( 'header', $data );
		$this->load->view ( 'category/index' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 跳转到添加分类页面
	 */
	public function add() {
		$data ['title'] = '添加分类 - '.SYSTEM_NAME;
		$this->load->view ( 'header', $data );
		$this->load->view ( 'category/add' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 跳转到编辑分类页面
	 */
	public function edit() {
		$id = $this->uri->segment(4);
		$this->load->model ( 'category_model' );
		$data ['category'] = $this->category_model->load ( $id );
		$data ['title'] = '编辑分类 - '.SYSTEM_NAME;
		$this->load->view ( 'header', $data );
		$this->load->view ( 'category/edit' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 保存或者更新分类的信息
	 */
	public function save() {
		$id = $this->input->post('id');
		$category = array (
				'name' => $this->input->post ( 'name' ),
				'description' => $this->input->post ( 'description' ) 
		);
		$this->load->model ( 'category_model' );
		if ($id) {
			if($this->category_model->update ( $id, $category )){
				return_json(TRUE,'','修改成功！'); 
			}else{
				return_json(FALSE,'','修改失败！');
			}
		} else {
			$categoryid=$this->category_model->create ( $category );
			if(!empty($categoryid)){
				return_json(TRUE,'','添加成功！'); 
			}else{
				return_json(FALSE,'','添加失败！');
			}
		}
	}
	/*
	 * 删除分类信息
	 */
	public function delete() {
		$id = $this->input->post('id');
		$this->load->model ( 'product_model' );
		$products = $this->product_model->find_by_cat ( $id );
		if (! empty ($products)) {
			return_json(FALSE,'','该分类下还有商品，请先删除该类商品！'); 
		}
		$this->load->model ( 'category_model' );
		if ($this->category_model->delete ( $id )) {
			return_json(TRUE,'','删除成功！'); 
		}else{
			return_json(TRUE,'','删除失败！');
		}
	}
}